package com.maple.exclusivesport.ui.main;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import com.maple.exclusivesport.R;

/**
 * Created by maple on 2019/10/18 19:05
 * E-Mail Address：740917401@qq.com
 */
public class MyFragmentPagerAdapter extends PagerAdapter {
    private Fragment[] fragments;
    private FragmentManager manager;
    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3};
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return context.getResources().getString(TAB_TITLES[position]);
    }
    Context context;
    public MyFragmentPagerAdapter(Context context,FragmentManager fm, Fragment[] fragments) {

        super();
        manager=fm;
        this.fragments = fragments;
        this.context=context;
    }


    @Override
    public int getCount() {
        return fragments.length;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = fragments[position];
        //判断当前的fragment是否已经被添加进入Fragmentanager管理器中
        if (!fragment.isAdded()) {
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(fragment, fragment.getClass().getSimpleName());
            //不保存系统参数，自己控制加载的参数
            transaction.commitAllowingStateLoss();
            //手动调用,立刻加载Fragment片段
            manager.executePendingTransactions();
        }
        if (fragment.getView().getParent() == null) {
            //添加布局
            container.addView(fragment.getView());
        }
        return fragment.getView();
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //移除布局
        container.removeView(fragments[position].getView());
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}
